package controllers

import "LoginTemplate/models"

type RoleController struct {
	BaseController
}

type Role struct {
	Id       int    `json:"id"`
	RoleName string `json:"role_name"`
}

// 添加角色
func (u *RoleController) InsertRole() {
	var role Role
	err := u.ShouldBind(&role)
	if err != nil {
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	if role.RoleName == "" {
		u.JsonMsg(500, "", "请输入部门名称")
	}
	sql := "insert into role ( role_name ) values ( ? )"
	tx := models.DB.Debug().Exec(sql, role.RoleName)
	if tx.Error != nil {
		u.JsonMsg(500, "", "失败")
	}
	u.JsonMsg(200, "", "成功")
}

// 修改角色
func (u *RoleController) UpdateRole() {
	var role Role
	err := u.ShouldBind(&role)
	if err != nil {
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	if role.RoleName == "" {
		u.JsonMsg(500, "", "请输入部门名称")
	}
	sql := "update role set role_name = ? where id = ?"
	tx := models.DB.Debug().Exec(sql, role.RoleName, role.Id)
	if tx.Error != nil {
		u.JsonMsg(500, "", "失败")
	}
	u.JsonMsg(200, "", "成功")
}

// 删除角色
func (u *RoleController) DeleteRole() {
	var role Role
	err := u.ShouldBind(&role)
	if err != nil {
		println(err.Error())
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	sql := "delete from role where id = ?"
	tx := models.DB.Debug().Exec(sql, role.Id)
	if tx.Error != nil {
		u.JsonMsg(500, "", "失败")
	}
	u.JsonMsg(200, "", "成功")
}

type RoleData struct {
	Code        int    `json:"code"`
	Msg         string `json:"msg"`
	Data        []Role `json:"data"`
	Sum         int    `json:"sum"`         //总页数
	CurrentPage int    `json:"currentPage"` //当前页
	TotalNumber int    `json:"totalNumber"` //总条数
}

// 查询角色
func (u *RoleController) SelectRole() {
	var pictureList PictureList
	err := u.ShouldBind(&pictureList)
	var sum int
	var totalNumber int
	if err != nil {
		println(err.Error())
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	var role []Role
	sql := "select * from role limit ? , ?"
	tx := models.DB.Debug().Raw(sql, (pictureList.Page-1)*pictureList.Size, pictureList.Size).Scan(&role)
	sqlsum := "SELECT CEIL(COUNT(*) / ? ) FROM role"
	models.DB.Debug().Raw(sqlsum, pictureList.Size).Scan(&sum)
	sqlNumBer := "select count(*) from role"
	models.DB.Debug().Raw(sqlNumBer).Scan(&totalNumber)
	if tx.Error != nil {
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	var picturedata RoleData
	picturedata.Code = 200
	picturedata.Data = role
	picturedata.Msg = "成功"
	picturedata.Sum = sum
	picturedata.CurrentPage = pictureList.Page
	picturedata.TotalNumber = totalNumber
	//return picturedata
	u.JsonMsg(200, map[string]interface{}{
		"list":  picturedata,
		"count": "",
	}, "success")
}
